<?php
/*-------------------------------------------------------------------------\
|
|  ========================================================
|  Fusion Registry GPL
|  Copyright (C) 2007 Fusion Scripts
|
|  This program is free software; you can redistribute it and/or
|  modify it under the terms of the GNU General Public License
|  as published by the Free Software Foundation; either version 2
|  of the License, or (at your option) any later version.
|
|  This program is distributed in the hope that it will be useful,
|  but WITHOUT ANY WARRANTY; without even the implied warranty of
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
|  GNU General Public License for more details.
|
|  You should have received a copy of the GNU General Public License
|  along with this program; if not, write to the Free Software
|  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
|  ========================================================
|
|  Email: info@fusionscripts.com
|  Web-Site: http://www.fusionscripts.com/
|
|  $Id: attach.php 4 2008-08-03 01:43:03Z registry.fusion $
|
\-------------------------------------------------------------------------*/

/**
 * 'registry_attach' class for the Fusion Registry.
 *
 * @package Fusion Registry
 * @version $Id: attach.php 4 2008-08-03 01:43:03Z registry.fusion $
 */

/**
 * Fusion Registry core require
 */
require_once(REGISTRY_PATH.'/lib/core.php');

/**
 * Class 'registry_attach' is in charge of the viewing, adding, deleting, and setting highlight attachments.
 *
 * This class should be invoked by the parent integration harness.
 * Most functions of this class do not have return values, instead the
 * redirect function is called to print a pretty thank you message to the
 * end user and stops the procedural code.
 *
 * @package Fusion Registry
 */
class registry_attach
{
    var $ipsclass;

    /**#@+ @var string */
    var $output     = "";
    var $page_title = "";
    /**#@-*/

    /**#@+ @var array */
    var $data            = array();
    var $registry_config = array();
    var $nav_bar         = array();
    var $html            = array( 'core', 'gallery' );
    var $lib             = array( 'upload', 'functions', 'custom_fields' );
    /**#@-*/

    /** @var object Fusion Registry core */
    var $core = "";

    /**
     * Invoked from parent harness, this executes the code.
     *
     * This is the only function which should be called from the harness.
     * This function is the traffic cop for this class, it should
     * do very little procedural code, if any.
     *
     * @param string $param Function to call
     */
    function auto_run($param='')
    {
        // Initialize core
        $this->core = new registry_core();
        $this->core->ipsclass =& $this->ipsclass;
        $this->core->auto_run(&$this);

        // Start our Nav Bar
        $this->nav_bar[] = "<a href='{$this->ipsclass->base_url}autocom=".REGISTRY_URL."'>".$this->ipsclass->lang['title']."</a>";

        // Which way to go?
        switch( $param )
        {
            case 'do_delete':
                $this->data['body'] = $this->do_delete();
                break;

            case 'do_new':
                $this->data['body'] = $this->do_new();
                break;

            case 'set_highlight':
                $this->data['body'] = $this->set_highlight();
                break;

            case 'view':
                $this->data['body'] = $this->view();
                break;

            case 'manage_menu':
            default:
                $this->data['body'] = $this->manage_menu();
                break;
        }

        // Let's create the common output elements now
        $this->data['navigation']     = $this->lib['functions']->do_navigation();
        $this->data['latest_updated'] = $this->lib['functions']->do_latest_updated();
        $this->data['my_cars']        = $this->lib['functions']->do_my_items();

        // Print it all out
        $this->output = $this->core->process_output();

        $this->ipsclass->print->add_output( $this->output );

        // Shall we use our Custom page title, or the default one?
        $this->page_title = empty($this->page_title) ? $this->ipsclass->lang['page_title'] : $this->page_title;

        // Set the title and nav bar, print the output
        $this->ipsclass->print->do_output( array( 'TITLE' => $this->ipsclass->vars['board_name'] .' -> '. $this->page_title,
                                                  'NAV'   => $this->nav_bar ) );
    }


    /**
     * Delete a gallery image, not undo-able
     *
     * @return string Failure returns template 'message'
     */
    function do_delete()
    {
        // For security measures we are going to make sure that the person
        // logged in is the owner of the image trying to be deleted.  So first
        // we need to select the item and find out who owns it ;)
        $this->ipsclass->DB->query( "SELECT g.id AS item_id, g.member_id, g.image_id AS highlight_id, images.attach_id,
                        images.attach_location, images.attach_hits, images.attach_ext, images.attach_file,
                        images.attach_thumb_location, gallery.image_id
                     FROM ibf_registry_images AS images
                         LEFT JOIN ibf_registry_gallery AS gallery ON gallery.image_id = images.attach_id
                        LEFT JOIN ibf_registry_items AS g ON g.id = gallery.item_id
                     WHERE gallery.id = '" . $this->ipsclass->input['id'] . "'");

        $image_data = $this->ipsclass->DB->fetch_row();

        // Now let's do the check
        if ( $this->ipsclass->member['id'] != $image_data['member_id'] )
        {
            if ( $this->ipsclass->member['g_is_supmod'] != 1 )
            {
                // Get them outta here, they don't own this item!!!
                $data = array(
                                message    => $this->ipsclass->lang['not_owner_failure'],
                                next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                                next_title => $this->ipsclass->lang['main_menu'],
                             );

                // Return the message
                return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
            }
        }

        // Delete images from DB
        $this->ipsclass->DB->query("DELETE FROM ibf_registry_gallery WHERE id='". $this->ipsclass->input['id'] ."'" );
        $this->ipsclass->DB->query("DELETE FROM ibf_registry_images WHERE attach_id='". $image_data['attach_id'] ."'" );

        // If this was the highlight, get rid of the entry in ibf_registry
        if ($image_data['attach_id'] == $image_data['highlight_id'])
        {
            $db_string = $this->ipsclass->DB->compile_db_update_string( array( image_id => '' ) );
            $this->ipsclass->DB->query("UPDATE ibf_registry_items SET $db_string WHERE id = '". $image_data['item_id'] ."'");
            unset($db_string);
        }

        // Delete highlight image from disk
        if (is_file($this->ipsclass->vars['upload_dir']."/".$image_data['attach_location']))
        {
            @unlink($this->ipsclass->vars['upload_dir']."/".$image_data['attach_location']);
        }

        // And the thumbnail
        if (is_file($this->ipsclass->vars['upload_dir']."/".$image_data['attach_thumb_location']))
        {
            @unlink($this->ipsclass->vars['upload_dir']."/".$image_data['attach_thumb_location']);
        }

        // Will be used to store the created and updated time in DB.
        // We are not using mysql's timestamp format because we are
        // control freaks :)
        $epoch_time = time();

        // Now we need to update the date_updated of the item entry itself
        $db_string = $this->ipsclass->DB->compile_db_update_string( array('date_updated' => $epoch_time) );

        // Execute the sql call
        $this->ipsclass->DB->query("UPDATE ibf_registry_items SET $db_string WHERE id = '" . $this->ipsclass->input['CID'] . "'");
        unset($db_string);

        // Present message
        $this->ipsclass->print->redirect_screen( $this->ipsclass->lang['delete_image_success'], "autocom=".REGISTRY_URL."&amp;cmd=manage_gallery&amp;CID={$this->ipsclass->input['CID']}" );
    }


    /**
     * Addition of new gallery image
     *
     * @return string Failure returns template 'message'
     */
    function do_new()
    {
        // Make sure they haven't exceeded the max image limit
        $this->ipsclass->DB->query( "SELECT count(images.image_id) AS total_images
                     FROM ibf_registry_gallery AS images
                        LEFT JOIN ibf_registry_items AS garage ON images.item_id = garage.id
                     WHERE garage.id = '" . $this->ipsclass->input['CID'] . "'" );

        $row = $this->ipsclass->DB->fetch_row();

        if ($row['total_images'] >= $this->registry_config['max_car_images'])
        {
            // Sorry, too many images :)
            $data = array(
                            message    => $this->ipsclass->lang['exceeded_gallery_limit'],
                            next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=manage_gallery&amp;CID={$this->ipsclass->input['CID']}",
                            next_title => $this->ipsclass->lang['manage_gallery'],
                         );

            // Return the message
            return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
        }

        // Grab that image, if they have permission!
        if ( $this->ipsclass->check_perms($this->registry_config['upload_perms']) == TRUE )
        {
            $sql_image_id = $this->lib['upload']->process_upload('registry_gallery', $this->ipsclass->input['CID']);

            // Record the uploaded image (if any)
            if ( is_int($sql_image_id) && ($this->lib['upload']->error_msg() == "") )
            {
                // Inset the registry_gallery row
                $db_string = $this->ipsclass->DB->compile_db_insert_string( array(
                                                                    'image_id' => $sql_image_id,
                                                                    'item_id' => $this->ipsclass->input['CID'],
                                                          )      );

                $this->ipsclass->DB->query("INSERT INTO ibf_registry_gallery (". $db_string['FIELD_NAMES']. ") VALUES (". $db_string['FIELD_VALUES'] .")");
            }
        }

        // Will be used to store the created and updated time in DB.
        // We are not using mysql's timestamp format because we are
        // control freaks :)
        $epoch_time = time();

        // Now we need to update the date_updated of the item entry itself
        $db_string = $this->ipsclass->DB->compile_db_update_string( array('date_updated' => $epoch_time) );

        // Execute the sql call
        $this->ipsclass->DB->query("UPDATE ibf_registry_items SET $db_string WHERE id = '" . $this->ipsclass->input['CID'] . "'");
        unset($db_string);

        // Do we need a line break?
        $error_text = $this->lib['upload']->error_msg();

        if ( empty($error_text) == FALSE )
        {
        	$error_text = $error_text = '<br />'. $error_text;
        }

        // Present message
        $this->ipsclass->print->redirect_screen( $this->ipsclass->lang['new_image_success'] . $error_text, "autocom=".REGISTRY_URL."&amp;cmd=manage_gallery&amp;CID={$this->ipsclass->input['CID']}" );
    }


    /**
     * Build the HTML menu for managing the gallery of an item
     *
     * @return string Success returns template 'manage_gallery'; Failure returns template 'message'
     */
    function manage_menu()
    {
        // For security measures we are going to make sure that the person
        //   logged in is the owner of the item trying to be modified.  So first
        //   we need to select the item and find out who owns it ;)
        $this->ipsclass->DB->query( "SELECT g.* FROM ibf_registry_items AS g WHERE g.id = '". $this->ipsclass->input['CID'] ."'" );

        $vehicle_data = $this->ipsclass->DB->fetch_row();

        // First let's grab the user's vehicle info
        $cf_entries = $this->lib['custom_fields']->get_cf_entries( array( 'WHERE' => "item_id='".$this->ipsclass->input['CID']."'" ) );

        // Setup our highlight for the title
        $cf_highlight = $this->lib['custom_fields']->get_cf_highlight();

        $data['highlight_field_value'] = '';

        foreach ( $cf_highlight as $cf_field_id => $cf_highlight_row )
        {
            $data['highlight_field_value'] .= $this->lib['custom_fields']->process_cf_value( array( 'def' => $cf_highlight_row,
                                                                                                    'value' => $cf_entries[$cf_field_id]['field_value'],
                                                                                                    'type' => 'view',
                                                                                           )      );
            // Append space for readability
            $data['highlight_field_value'] .= ' ';
        }

        // Now let's do the check
        if ( $this->ipsclass->member['id'] != $vehicle_data['member_id'] )
        {
            if ( $this->ipsclass->member['g_is_supmod'] != 1 )
            {
                // Get them outta here, they don't own this item!!!
                $data = array(
                                message    => $this->ipsclass->lang['not_owner_failure'],
                                next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                                next_title => $this->ipsclass->lang['main_menu'],
                             );

                // Return the message
                return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
            }
        }

        // Got attachment types?
        if ( ! is_array( $this->ipsclass->cache['attachtypes'] ) )
        {
            $this->ipsclass->cache['attachtypes'] = array();

            $this->ipsclass->DB->simple_construct( array( 'select' => 'atype_extension,atype_mimetype,atype_post,atype_photo,atype_img', 'from' => 'attachments_type', 'where' => "atype_photo=1 OR atype_post=1" ) );
            $this->ipsclass->DB->simple_exec();

            while ( $r = $this->ipsclass->DB->fetch_row() )
            {
                $this->ipsclass->cache['attachtypes'][ $r['atype_extension'] ] = $r;
            }
        }

        // Grab all the current gallery images for this item
        $image_query_id = $this->ipsclass->DB->query( "SELECT gallery.id, images.attach_id, images.attach_hits, images.attach_ext, images.attach_location,
                                            images.attach_is_image, images.attach_file, images.attach_thumb_location,
                                            garage.image_id AS highlight_image_id, gallery.image_id
                                       FROM ibf_registry_images AS images
                                            LEFT JOIN ibf_registry_gallery AS gallery ON images.attach_id = gallery.image_id
                                            LEFT JOIN ibf_registry_items AS garage ON gallery.item_id = garage.id
                                       WHERE garage.id = '" . $this->ipsclass->input['CID'] . "'" );

        $data['images_html'] = '';
        while ( $image_row = $this->ipsclass->DB->fetch_row($image_query_id) )
        {
            // Is this the vehicle highlight image?
            $image_highlight = '';
            if ( $image_row['highlight_image_id'] == $image_row['image_id'] )
            {
                // Yup, don't print select button
                $image_highlight = '<i>'.$this->ipsclass->lang['selected_highlight'].'</i>';

            }
            else
            {
                // Nope, give them the select button!
                $image_highlight = "<a href='{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=set_highlight&amp;id={$image_row['image_id']}&amp;CID={$this->ipsclass->input['CID']}' title='{$this->ipsclass->lang['set_highlight']}'>[{$this->ipsclass->lang['set_highlight']}]</a>";
            }

            if ( $image_row['attach_is_image'] )
            {
                // Do we have a thumbnail?  If so, our job is simple here :)
                if ( (empty($image_row['attach_thumb_location']) == FALSE) AND
                     (@file_exists($this->ipsclass->vars['upload_dir']."/".$image_row['attach_thumb_location'])) AND
                     ($image_row['attach_thumb_location'] != $image_row['attach_location']) )
                {
                    // Form the correct image link if it's remote
                    $image_link = "{$this->ipsclass->vars['upload_url']}/{$image_row['attach_thumb_location']}";

                    // Yippie, our thumbnail is already made for us :)
                    $data['images_html'] .= $this->ipsclass->compiled_templates['skin_registry_gallery']->manage_gallery_item_thumb( array(  'filename'  => $image_link,
                                                                                                       'hits'      => $image_row['attach_hits'],
                                                                                                       'type'      => 'registry_gallery',
                                                                                                       'id'        => $image_row['id'],
                                                                                                       'CID'       => $this->ipsclass->input['CID'],
                                                                                                       'highlight' => $image_highlight,
                                                                                             )      );
                }
                else
                {
                    // Since we don't have a pre-made thumb we are going
                    //   to fall back on the old style :(
                    $img_size = array();

                    // Is this a remote image?
                    if ( ($image_row['attach_thumb_location'] == "remote" ) OR preg_match("/^http:\/\//i", $image_row['attach_location']) )
                    {
                        $img_size = @GetImageSize( $image_row['attach_location'] );
                    }
                    else
                    {
                        $img_size = @GetImageSize( $this->ipsclass->vars['upload_url']."/".$image_row['attach_location'] );
                    }

                    if ( $img_size[0] < 1 )
                    {
                        $img_size    = array();
                        $img_size[0] = $this->registry_config['thumbnail_resolution'] + 1;
                        $img_size[1] = $this->registry_config['thumbnail_resolution'] + 1;
                    }

                    // Form the correct image link if it's remote
                    $image_link = ( ($image_row['attach_thumb_location'] == "remote")  OR preg_match("/^http:\/\//i", $image_row['attach_location']) )
                                ? $image_row['attach_location']
                                : "{$this->ipsclass->vars['upload_url']}/{$image_row['attach_location']}";

                    //----------------------------------------------------
                    // Do we need to scale?
                    //----------------------------------------------------

                    if ( ( $img_size[0] <= $this->registry_config['thumbnail_resolution'] ) AND
                         ( $img_size[1] <= $this->registry_config['thumbnail_resolution'] ) )
                    {
                        $data['images_html'] .= $this->ipsclass->compiled_templates['skin_registry_gallery']->manage_gallery_item_thumb(
                                                    array(  'filename'  => $image_link,
                                                            'hits'      => $image_row['attach_hits'],
                                                            'type'      => 'registry_gallery',
                                                            'id'        => $image_row['id'],
                                                            'CID'       => $this->ipsclass->input['CID'],
                                                            'highlight' => $image_highlight,
                                                   )      );
                    }
                    else
                    {
                        $im = $this->ipsclass->scale_image( array( 'max_width'  => $this->registry_config['thumbnail_resolution'],
                                                                   'max_height' => $this->registry_config['thumbnail_resolution'],
                                                                   'cur_width'  => $img_size[0],
                                                                   'cur_height' => $img_size[1]
                                                          )      );

                        $data['images_html'] .= $this->ipsclass->compiled_templates['skin_registry_gallery']->manage_gallery_item(
                                                    array( 'filename'  => $image_link,
                                                           'width'     => $im['img_width'],
                                                           'height'    => $im['img_height'],
                                                           'hits'      => $image_row['attach_hits'],
                                                           'type'      => 'registry_gallery',
                                                           'id'        => $image_row['id'],
                                                           'CID'       => $this->ipsclass->input['CID'],
                                                           'highlight' => $image_highlight,
                                                   )      );
                    } // End if scale
                } // End if thumbnail
            } // End if image
            else
            {
                // This appears to be a non-image attachment, let's show it!
                $tmp = $this->ipsclass->compiled_templates['skin_registry_core']->show_attachments(
                            array ( 'image'  => $this->ipsclass->cache['attachtypes'][ $image_row['attach_ext'] ]['atype_img'],
                                     'name'   => $image_row['attach_file'],
                                     'id'     => $image_row['id'],
                                     'type'   => 'registry_gallery',
                            )      );

                $data['images_html'] .= $this->ipsclass->compiled_templates['skin_registry_gallery']->manage_gallery_item_attach(
                                            array( 'attach_data' => $tmp,
                                                   'id'          => $image_row['id'],
                                                   'CID'         => $this->ipsclass->input['CID'],
                                                   'highlight'   => '<i>'.$this->ipsclass->lang['invalid_highlight'].'</i>',
                                          )      );
            }
        } // End while $image_row

        // If they are allowed to upload images, let's prepare the HTML
        $data['add_new_image'] = '';

        if ( ($this->registry_config['allow_image_upload'] == 1) and
             ($this->registry_config['max_image_kbytes'] > 0) and
             ($this->ipsclass->check_perms($this->registry_config['upload_perms']) == TRUE) )
        {
            // Do they have enough images yet?
            $this->ipsclass->DB->query( "SELECT count(images.image_id) AS total_images
                                         FROM ibf_registry_gallery AS images
                                            LEFT JOIN ibf_registry_items AS garage ON images.item_id = garage.id
                                         WHERE garage.id = '" . $this->ipsclass->input['CID'] . "'" );

            $row = $this->ipsclass->DB->fetch_row();

            if ($row['total_images'] >= $this->registry_config['max_car_images'])
            {
                // Don't show the upload form if they have hit the limit!
                $data['add_new_image'] = $this->ipsclass->compiled_templates['skin_registry_gallery']->manage_gallery_exceeded();
            }
            else
            {
                // Looks like they still have some space left, continue on!
                $size_string = $this->ipsclass->size_format( $this->registry_config['max_image_kbytes'] * 1024 );


                $upload_data['upload'] = $this->ipsclass->compiled_templates['skin_registry_core']->upload_field( $size_string, $this->registry_config['max_image_resolution'] );

                // If they are allowed to use url images, prep the HTML
                if ( $this->registry_config['allow_image_url'] == 1 )
                {
                     $upload_data['upload_url'] = $this->ipsclass->compiled_templates['skin_registry_core']->upload_url_field( array( url => 'http://',
                                                                                                                                      target_form => 'new_gallery_image'
                                                                                                                             )      );
                }

                // Setup the form HTML
                $data['add_new_image'] = $this->ipsclass->compiled_templates['skin_registry_gallery']->manage_gallery_new_image($upload_data);
            }
        }

        // Pass along the vehicle id
        $data['CID'] = $this->ipsclass->input['CID'];

        // If they don't have any existing images let's display a nice message
        if ( empty($data['images_html']) == TRUE )
        {
            $data['images_html'] = '<tr><td colspan="3" class="post1" align="center"><br /><i>'.$this->ipsclass->lang['no_gallery_images'].'</i><br />&nbsp;</td></tr>';
        }

        // Grab our nifty popup code
        $data['popup_javascript'] = $this->ipsclass->compiled_templates['skin_registry_core']->popup_javascript();

        // Set page title
        $this->page_title = $this->ipsclass->lang['manage_gallery'];

        // Add to our Nav Bar
        $this->nav_bar[] = "<a href='{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=manage_item&amp;CID={$this->ipsclass->input['CID']}'>{$data['highlight_field_value']}</a>";

        return $this->ipsclass->compiled_templates['skin_registry_gallery']->manage_gallery_menu($data);
    }


    /**
     * Set the highlight image for a vehicle
     *
     * @return string Failure returns template 'message'
     */
    function set_highlight()
    {
        // For security measures we are going to make sure that the person
        // logged in is the owner of the item.  So first we need to select the
        // item and find out who owns it ;)
        $this->ipsclass->DB->query( "SELECT * FROM ibf_registry_items WHERE id = '" . $this->ipsclass->input['CID'] . "'");

        $vehicle_data = $this->ipsclass->DB->fetch_row();

        // Now let's do the check
        if ( $this->ipsclass->member['id'] != $vehicle_data['member_id'] )
        {
            if ( $this->ipsclass->member['g_is_supmod'] != 1 )
            {
                // Get them outta here, they don't own this vehicle!!!
                $data = array(
                                message    => $this->ipsclass->lang['not_owner_failure'],
                                next       => "{$this->ipsclass->base_url}autocom=".REGISTRY_URL."&amp;cmd=idx",
                                next_title => $this->ipsclass->lang['main_menu'],
                             );

                // Return the message
                return $this->ipsclass->compiled_templates['skin_registry_core']->message($data);
            }
        }

        // Will be used to store the created and updated time in DB.
        // We are not using mysql's timestamp format because we are
        // control freaks :)
        $epoch_time = time();

        // This constructs the FIELD_NAMES and FIELD_VALUES for sql
        $db_string = $this->ipsclass->DB->compile_db_update_string( array( 'image_id'     => $this->ipsclass->input['id'],
                                                                           'date_updated' => $epoch_time,
                                                                  )      );

        // Execute the sql call
        $this->ipsclass->DB->query("UPDATE ibf_registry_items SET $db_string WHERE id='". $this->ipsclass->input['CID'] ."'");
        unset($db_string);

        // Present message
        $this->ipsclass->print->redirect_screen( $this->ipsclass->lang['set_highlight_success'], "autocom=".REGISTRY_URL."&amp;cmd=manage_gallery&amp;CID={$this->ipsclass->input['CID']}" );
    }


    /**
     * Pipe image to end user
     *
     * Ideal situation is this function prevents hotlinking to images
     * if the admin has disabled guests from browsing the Fusion Registry.
     */
    function view()
    {
        // Do they have permission to browse?
        if ( $this->ipsclass->check_perms($this->registry_config['browse_perms']) != TRUE )
        {
            $this->ipsclass->Error( array( LEVEL => 1, MSG => 'no_permission') );
        }

        $this->ipsclass->input['id'] = preg_replace( "/^(\d+)$/", "\\1", $this->ipsclass->input['id'] );

        if ($this->ipsclass->input['id'] == "")
        {
            $this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'missing_files' ) );
        }

        // Got attachment types?
        if ( ! is_array($this->ipsclass->cache['attachtypes']) )
        {
            $this->ipsclass->cache['attachtype'] = array();

            $this->ipsclass->DB->simple_construct( array( 'select' => 'atype_extension,atype_mimetype,atype_post,atype_photo,atype_img', 'from' => 'attachments_type', 'where' => "atype_photo=1 OR atype_post=1" ) );
            $this->ipsclass->DB->simple_exec();

            while ( $r = $this->ipsclass->DB->fetch_row() )
            {
                $this->ipsclass->cache['attachtypes'][ $r['atype_extension'] ] = $r;
            }
        }

        // Handle correct 'type' of attachments.

        if ( $this->ipsclass->input['type'] == 'registry' )
        {
            $this->ipsclass->DB->query("SELECT g.id, images.attach_id, images.attach_ext, images.attach_file, images.attach_location
                                        FROM ibf_registry_items AS g LEFT JOIN ibf_registry_images AS images ON g.image_id = images.attach_id
                                        WHERE g.id='".$this->ipsclass->input['id']."'");
        }
        elseif ( $this->ipsclass->input['type'] == 'registry_mod' )
        {
            $this->ipsclass->DB->query("SELECT mods.id, images.attach_id, images.attach_ext, images.attach_file, images.attach_location
                                        FROM ibf_registry_mods AS mods LEFT JOIN ibf_registry_images AS images ON mods.image_id = images.attach_id
                                        WHERE mods.id='".$this->ipsclass->input['id']."'");
        }
        elseif ( $this->ipsclass->input['type'] == 'registry_gallery' )
        {
            $this->ipsclass->DB->query("SELECT gallery.id, images.attach_id, images.attach_ext, images.attach_file, images.attach_location
                                        FROM ibf_registry_gallery AS gallery LEFT JOIN ibf_registry_images AS images ON gallery.image_id = images.attach_id
                                        WHERE gallery.id='".$this->ipsclass->input['id']."'");
        }

        if ( !$this->ipsclass->DB->get_num_rows() )
        {
            $this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'is_broken_link' ) );
        }

        $data = $this->ipsclass->DB->fetch_row();

        if ( $data['attach_id'] == "" )
        {
            $this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'missing_files' ) );
        }

        // Update the "hits"..
        $this->ipsclass->DB->simple_construct( array( 'update' => 'registry_images', 'set' =>"attach_hits=attach_hits+1", 'where' => "attach_id=".$data['attach_id'] ) );
        $this->ipsclass->DB->simple_exec();

        // Check to see if this is a remote image
        if ( preg_match( "/^http:\/\//i", $data['attach_location']) )
        {
            // Redirect them to the remote image
            header("Location: ".$data['attach_location']);
            exit;
        }
        else
        {
            // Looks like a local file, show it!
            $file = $this->ipsclass->vars['upload_dir']."/".$data['attach_location'];

            if ( @file_exists( $file ) and ( $this->ipsclass->cache['attachtypes'][ $data['attach_ext'] ]['atype_mimetype'] != "" ) )
            {
                // Set up the headers, if they haven't already been sent
                if ( headers_sent() == 0 )
                {
                    header( "Content-Type: ".$this->ipsclass->cache['attachtypes'][ $data['attach_ext'] ]['atype_mimetype'] );
                    header( "Content-Disposition: inline; filename=\"".$data['attach_file']."\"" );
                    header( "Content-Length: ".(string)(filesize( $file ) ) );
                }

                // Open and display the file..
                $fh = fopen( $file, 'rb' );  // Set binary for Win even if it's an ascii file, it won't hurt.
                fpassthru( $fh );
                @fclose( $fh );
                exit();
            }
            else
            {
                // File does not exist..
                $this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'missing_files' ) );
            }
        }

        // Prevent the HTML wrapper from printing
        exit;
    }
}